package cc.flybb.words;

import android.app.Application;
import androidx.lifecycle.LiveData;
import java.util.List;

public class WordRepository {

    private WordDao wordDao;
    private LiveData<List<Word>> allWordsLive;


    // Note that in order to unit test the WordRepository, you have to remove the Application
    // dependency. This adds complexity and much more code, and this sample is not about testing.
    // See the BasicSample in the android-architecture-components repository at
    // https://github.com/googlesamples
    WordRepository(Application application) {
        WordDatabase wordDatabase = WordDatabase.getDatabase(application);
        wordDao = wordDatabase.getWordDao();
        allWordsLive = wordDao.getAllWordsLive();
    }

    // Room executes all queries on a separate thread.
    // Observed LiveData will notify the observer when the data has changed.
    LiveData<List<Word>> getAllWords() {
        return allWordsLive;
    }

    LiveData<List<Word>> findWordsWithPattern(String pattern) {
        return wordDao.findWordsWithPattern("%" + pattern + "%");
    }

//    public WordDao getWordDao() {
//        return wordDao;
//    }

    // You must call this on a non-UI thread or your app will throw an exception. Room ensures
    // that you're not doing any long running operations on the main thread, blocking the UI.
    void insertWords(final Word... words) {
        WordDatabase.databaseWriteExecutor.execute(new Runnable() {
            @Override
            public void run() {
                wordDao.insertWords(words);
            }
        });
    }

    void updateWords(final Word... words) {
        WordDatabase.databaseWriteExecutor.execute(new Runnable() {
            @Override
            public void run() {
                wordDao.updateWords(words);
            }
        });
    }

    void deleteWords(final Word... words) {
        WordDatabase.databaseWriteExecutor.execute(new Runnable() {
            @Override
            public void run() {
                wordDao.deleteWords(words);
            }
        });
    }

    void deleteAllWords() {
        WordDatabase.databaseWriteExecutor.execute(new Runnable() {
            @Override
            public void run() {
                wordDao.deleteAllWords();
            }
        });
    }

}
